package com.zhdl.modules.tools.web;

public class IntToHexUtil {
    public static String longToHex(long value) {
        StringBuilder sb = new StringBuilder(18);
        writeHex(sb, value, 16, "");
        return sb.toString();
    }

    public static String intToHex(int value) {
        StringBuilder sb = new StringBuilder(10);
        writeHex(sb, (long) value & 4294967295L, 8, "");
        return sb.toString();
    }

    public static String shortToHex(int value) {
        StringBuilder sb = new StringBuilder(6);
        writeHex(sb, (long) value & 65535L, 4, "");
        return sb.toString();
    }

    public static String byteToHex(int value) {
        StringBuilder sb = new StringBuilder(4);
        writeHex(sb, (long) value & 255L, 2, "");
        return sb.toString();
    }

    private static void writeHex(StringBuilder sb, long value, int nDigits, String prefix) {
        sb.append(prefix);
        char[] buf = new char[nDigits];
        long acc = value;

        for (int i = nDigits - 1; i >= 0; --i) {
            int digit = (int) (acc & 15L);
            buf[i] = (char) (digit < 10 ? 48 + digit : 65 + digit - 10);
            acc >>>= 4;
        }

        sb.append(buf);
    }

    public static String HeightLowRollBack(String hex) {
        if (hex.length() == 8) {
            return hex.substring(4, 8) + hex.substring(0, 4);
        }
        return hex;
    }

}
